package com.carleasoft.mps.core.async;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 * @author: haoyi
 */
@Configuration
@EnableAsync
public class TaskExecutorPool {

    @Bean("taskExecutor")
    public Executor getTaskExecutor(){
        Executors.newCachedThreadPool();
        //Executors.newFixedThreadPool();
        //设置了太大的corePoolSize和maxPoolSize可能还会因为线程上下文频繁切换降低任务处理速度
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        taskExecutor.setCorePoolSize(20);
        //配置最大线程数
        taskExecutor.setMaxPoolSize(50);
        //配置队列大小
        taskExecutor.setQueueCapacity(200);
        //允许的空闲时间
        taskExecutor.setKeepAliveSeconds(60);
        //拒绝执行策略
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        taskExecutor.initialize();
        return taskExecutor;
    }
}
